import React, { useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
import { userUploadAvatar } from "@/apis/userApi.ts";
import { Button, Form, Input, Upload, message } from "antd";
import { UploadFile } from "antd/lib/upload/interface";
import { updateUserInfo } from "@/apis/userApi.ts";
import { useDispatch } from "react-redux";
import { setUserAvatar } from "@/store/UserInfo/index.ts";

const { TextArea } = Input;

const normFile = (e: any) => {
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};

const UserInfoChange: React.FC = () => {
  const dispatch = useDispatch();
  console.log("UserInfoChange is rendering");

  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const onFinish = async (values: {
    nickname: string;
    password: string;
    description: string;
  }) => {
    const res = await updateUserInfo(values);
    if (res.code === 200) {
      message.success("修改成功");
    } else {
      message.error("修改失败");
    }
  };

  // 处理文件上传前的操作
  const beforeUpload = async (file: File) => {
    try {
      const response = await userUploadAvatar(file);
      const newFile: UploadFile = {
        uid: String(Date.now()), // 将 Date.now() 转换成字符串
        name: file.name,
        status: "done",
        url: response.data?.avatar,
      };
      setFileList([...fileList, newFile]);
      message.success("上传成功");
      // 更新用户的头像信息
      dispatch(setUserAvatar(response.data?.avatar!));

      // 阻止默认上传行为
      return false;
    } catch (error) {
      message.error("上传失败");
      return false; // 阻止默认上传行为
    }
  };

  // 自定义删除逻辑
  const onRemove = (file: UploadFile) => {
    const index = fileList.indexOf(file);
    const newFileList = [...fileList];
    newFileList.splice(index, 1);
    setFileList(newFileList);
  };

  return (
    <div
      style={{
        display: "flex",
        margin: "0 auto",
        justifyContent: "center",
        alignItems: "flex-start", // 垂直方向上不居中
        width: "80%",
        maxWidth: "1000px",
      }}
    >
      <Form
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 14 }}
        layout="horizontal"
        style={{ maxWidth: 600, width: "100%" }}
        onFinish={onFinish}
      >
        <Form.Item label="昵称" name="nickname">
          <Input />
        </Form.Item>
        <Form.Item label="密码" name="password">
          <Input />
        </Form.Item>
        <Form.Item label="描述" name="description">
          <TextArea rows={4} />
        </Form.Item>
        <Form.Item
          label="上传"
          valuePropName="fileList"
          getValueFromEvent={normFile}
        >
          <Upload
            listType="picture-card"
            fileList={fileList}
            beforeUpload={beforeUpload}
            onRemove={onRemove} // 提供自定义的删除逻辑
          >
            {fileList.length >= 1 ? null : (
              <button style={{ border: 0, background: "none" }} type="button">
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传</div>
              </button>
            )}
          </Upload>
        </Form.Item>
        <Form.Item
          style={{
            display: "flex",
            justifyContent: "center", // 提交按钮水平居中
            width: "100%",
          }}
        >
          <Button
            style={{ width: "150px" }}
            block
            type="primary"
            htmlType="submit"
          >
            确认修改
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default UserInfoChange;
